<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true">
      <el-form-item :label="t('interview.fields.batchId')" prop="batchId">
        <el-select
          v-model="queryParams.batchId"
          :placeholder="t('common.selectTextPlaceholder') + t('interview.fields.batchId')"
          clearable
          class="!w-160px"
          @change="handleQuery"
        >
          <el-option
            v-for="(item, index) in batchOptions"
            :key="index"
            :label="item.batchName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('interview.fields.interviewDate')" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          :start-placeholder="t('common.startTimeText')"
          :end-placeholder="t('common.endTimeText')"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          {{ t('common.search') }}
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          {{ t('common.reset') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <vxe-toolbar ref="toolbarRef" custom />
    <vxe-table
      id="iInterviewSpecialist-table"
      ref="tableRef"
      v-loading="loading"
      :data="list"
      stripe
      :custom-config="vxeTableConfig"
      :column-config="{ resizable: true }"
      :size="vxeTableSize"
    >
      <vxe-column :title="t('common.index')" type="seq" field="seq" width="60" align="center" />
      <vxe-column
        :title="t('interview.fields.batchId')"
        field="batchId"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      >
        <template #default="scope">
          {{ batchOptions.find((item) => item.id === scope.row.batchId)?.batchName }}
        </template>
      </vxe-column>
      <vxe-column
        :title="t('interview.fields.status')"
        field="status"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      >
        <template #default="scope">
          {{ calculateStatus(scope.row) }}
        </template>
      </vxe-column>
      <vxe-column
        :title="t('interview.fields.interviewDate')"
        field="interviewDate"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
        :formatter="vxeDateFormatter2"
      />
      <vxe-column
        :title="t('interview.fields.groups')"
        field="groupName"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('interview.fields.interviewTimes')"
        field="interviewTimes"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('interviewGroup.fields.meetingNumber')"
        field="meetingNumber"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('interviewGroup.fields.meetingPassword')"
        field="meetingPassword"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
        :visible="false"
      />
      <vxe-column
        :title="t('interviewGroup.fields.qqGroupNumber')"
        field="qqGroupNumber"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('interviewGroup.fields.specialistId1')"
        field="specialistName1"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('interviewGroup.fields.specialistId2')"
        field="specialistName2"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('interviewGroup.fields.specialistId3')"
        field="specialistName3"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('interview.fields.studentCount')"
        field="amount"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('common.operate')"
        field="operator"
        align="center"
        fixed="right"
        width="180"
      >
        <template #default="scope">
          <el-button link type="primary" @click="handleInterviewScene(scope.row)">
            {{ t('interviewGroup.specialist.interviewScene') }}
          </el-button>
          <el-button link type="primary" @click="handleStudentInfoList(scope.row)">
            {{ t('interviewGroup.specialist.studentInfos') }}
          </el-button>
        </template>
      </vxe-column>
    </vxe-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <RecruitStudentListInInterviewForSpecialist ref="studentListRef" />
</template>

<script setup lang="ts">
import { vxeDateFormatter2 } from '@/utils/formatTime'
import type { VxeTableInstance, VxeTablePropTypes, VxeToolbarInstance } from 'vxe-table'
import { useAppStore } from '@/store/modules/app'
import { BatchApi, BatchVO } from '@/api/recruit/batch'
import RecruitStudentListInInterviewForSpecialist from '@/views/recruit/recruitstudent/components/RecruitStudentListInInterviewForSpecialist.vue'
import { InterviewGroupApi, InterviewGroupSpecialListRespVO } from '@/api/recruit/interviewgroup'

/** 我的面试 列表 */
defineOptions({ name: 'InterviewSpecialist' })

const router = useRouter() // 路由
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const toolbarRef = ref<VxeToolbarInstance>()
const tableRef = ref<VxeTableInstance>()

const loading = ref(true) // 列表的加载中
const list = ref<InterviewGroupSpecialListRespVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  batchId: undefined,
  interviewId: undefined,
  groupName: undefined,
  meetingNumber: undefined,
  meetingPassword: undefined,
  qqGroupNumber: undefined,
  specialistId1: undefined,
  specialistId2: undefined,
  specialistId3: undefined,
  remark: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const vxeTableConfig: VxeTablePropTypes.CustomConfig = {
  storage: true,
  mode: 'drawer',
  checkMethod({ column }) {
    return !['seq', 'operator'].includes(column.field)
  }
}

const appStore = useAppStore()
const vxeTableSize = computed(() => appStore.getCurrentSizeVxe)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await InterviewGroupApi.getInterviewGroupSpecialistPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const batchOptions = ref<BatchVO[]>([])
const getBatchSelectOptions = async () => {
  batchOptions.value = await BatchApi.getSelectList()
}

// 根据时间判断状态，未到面试日期则是未开始，面试前一天状态是即将开始，面试当天并起始时间未结束则是进行中，已过面试日期则是已结束
const calculateStatus = (row: InterviewGroupSpecialListRespVO) => {
  const now = new Date()
  const interviewDate = new Date(row.interviewDate)

  // 获取面试当天的开始和结束时间
  const startDateTime = new Date(interviewDate)
  const endDateTime = new Date(interviewDate)

  const [startHour, startMinute, startSecond] = row.interviewStartTime.split(':').map(Number)
  const [endHour, endMinute, endSecond] = row.interviewEndTime.split(':').map(Number)

  startDateTime.setHours(startHour, startMinute, startSecond, 0)
  endDateTime.setHours(endHour, endMinute, endSecond, 0)

  if (now < startDateTime) {
    return t('interview.status.notStarted')
  } else if (now >= startDateTime && now < endDateTime) {
    return t('interview.status.ongoing')
  } else if (now >= endDateTime) {
    return t('interview.status.ended')
  } else {
    // 面试前一天
    const oneDayBefore = new Date(interviewDate)
    oneDayBefore.setDate(interviewDate.getDate() - 1)

    if (now >= oneDayBefore && now < startDateTime) {
      return t('interview.status.comingSoon')
    }
  }
}

const studentListRef = ref<InstanceType<typeof RecruitStudentListInInterviewForSpecialist>>()
const handleStudentInfoList = (row: InterviewGroupSpecialListRespVO) => {
  studentListRef.value?.open(row)
}

const handleInterviewScene = (row: InterviewGroupSpecialListRespVO) => {
  router.push(`/recruit/interview-scene/${row.groupId}`)
}

/** 初始化 **/
onMounted(async () => {
  await getBatchSelectOptions()
  // 然后查询最新计划的数据
  queryParams.batchId = batchOptions.value[0]?.id ?? undefined
  getList()

  const table = tableRef.value
  const toolbar = toolbarRef.value
  if (table && toolbar) {
    table.connect(toolbar)
  }
})
</script>

<style lang="scss" scoped>
:deep(.vxe-cell .el-button + .el-button) {
  margin-left: 0;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 15px !important;
}
</style>
